#pragma once

#include "windows.h"

template<typename T>
class lazy
{
public:
    lazy()
        : t(NULL)
    {}

    ~lazy()
    {
        if (t!=NULL)
        {
            delete (T*) t;
            t = NULL;
        }
    }

    T * operator -> ()
    {
        return getInstanceInSafe();
    }

    T& operator * ()
    {
        return * getInstanceInSafe();
    }

private:

    lazy(const lazy &);
    lazy & operator = (const lazy &);

    inline T* getInstanceInSafe()
    {
        if (t == NULL)
        {
            InterlockedCompareExchange(&t, (address_type) new T(), NULL);
        }

        return (T*) t;
    }

    typedef unsigned int address_type;
    volatile address_type t;
};